import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_cache_manager/src/storage/file_system/file_system_io.dart';
import 'package:path_provider/path_provider.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/models/gift/xindong_gift_class.dart';
import 'package:xindong/utils/xindong_text_util.dart';

/// 缓存助手
/// 依赖插件：path_provider
class XinDongCacheUtil {
  /// 加载缓存大小
  static Future<String> loadCache() async {
    try {
      // 临时文件目录
      Directory tempDirectory = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDirectory);

      // 图片缓存目录
      value += ImageCache().currentSizeBytes;

      return _renderSize(value);
    } catch (error) {
      return _renderSize(0);
    }
  }

  static Future<String> clearCache() async {
    try {
      ImageCache().clear();
      XinDongCacheSingleton.instance.emptyCache();
      // 临时文件目录
      Directory tempDirectory = await getTemporaryDirectory();
      await deleteDirectory(tempDirectory);
      return _renderSize(0);
    } catch (error) {
      return _renderSize(0);
    }
  }

  static Future _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children) {
        total += await _getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }

  static _renderSize(double? value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = ['Byte', 'KB', 'MB', 'GB'];
    int index = 0;
    while (value! > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  /// 递归方式删除目录
  static Future<void> deleteDirectory(FileSystemEntity file) async {
    try {
      // 删除临时文件目录
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await deleteDirectory(child);
        }
      }
      await file.delete();
    } catch (e) {
      mCatchPrint(e);
    }
  }
}

class XinDongCacheSingleton {
  static const key = 'customCacheKey';
  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 7),
      maxNrOfCacheObjects: 50,
      repo: JsonCacheInfoRepository(databaseName: key),
      fileSystem: IOFileSystem(key),
      fileService: HttpFileService(),
    ),
  );

  /// 缓存礼物特效动画
  /// 移动网络不静默下载
  static void cacheGiftSVGA(List<XinDongGiftClass> dataList) async {
    // if (XinDongConnectivityProvider.instance.connectionStatus == ConnectivityResult.mobile) {
    //   return;
    // }
    if (dataList.isEmpty) {
      return;
    }
    for (XinDongGiftClass model in dataList) {
      if (!TextUtil.isEmpty(model.cover)) {
        // downloadFile每次都下载新文件（不推荐）
        // getSingleFile每次会检查是否有缓存，有就直接返回，没有下载就加载
        // flutter: /var/mobile/Containers/Data/Application/44267342-36E7-4122-88C0-76361C6F1C9D/Library/Caches/customCacheKey/6e43bea0-c838-11ec-9169-f519b33ed4f9.bin
        final info = await XinDongCacheSingleton.instance.getSingleFile(model.cover!);
        // XinDongGiftAnimationOverlay.instance.addQueue(SVGAClass(
        //   type: SVGAType.receiveGift,
        //   name: model.name,
        //   svga: model.svga ?? "",
        // ));
      }
    }
    mDebugPrint("缓存礼物结束");
  }
}
